﻿using System;
using System.Collections.Generic;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using NHibernate;
using NHibernate.Criterion;

namespace Cms.Data
{
    public class CategoryRepository : BaseRepository, ICategoryRepository
    {
        public CategoryRepository()
        {
        }

        public CategoryRepository(ISession session)
            : base(session)
        {
        }

        #region ICategoryRepository Members

        public Category GetCategory(int id)
        {
            return Session.Get<Category>(id);
        }

        public void DeleteCategory(Category category)
        {
            DeleteEntity(category, "ContentRepository.DeleteCategory");
        }

        public void SaveCategory(Category category)
        {
            SaveEntity(category, "ContentRepository.SaveCategory");
        }

        public bool CategoryExists(string name, int id, int siteID)
        {
            string hql = "from Category c where c.Name = :name and c.Site.ID = " + siteID;
            if (id > 0)
            {
                hql += " and c.ID <> " + id;
            }
            IList<Category> categories = Session.CreateQuery(hql)
                .SetString("name", name)
                .List<Category>();
            return categories.Count > 0;
        }

        public bool CategoryFolderNameExists(string folderName, int id, int siteID)
        {
            string hql = "from Category c where c.FolderName = :name and c.Site.ID = " + siteID;
            if (id > 0)
            {
                hql += " and c.ID <> " + id;
            }
            IList<Category> categories = Session.CreateQuery(hql)
                .SetString("name", folderName)
                .List<Category>();
            return categories.Count > 0;
        }

        #endregion
    }
}